package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 用户下单
     *
     * @param dto
     */
    @Override
    public void submit(OrdersSubmitDTO dto) {
        Orders orders = new Orders();
        //拷贝公共属性到订单实体
        BeanUtils.copyProperties(dto,orders);
        //设置订单号
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        //设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置下单用户
        orders.setUserId(BaseContext.getCurrentId());
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态
        orders.setPayStatus(0);
        //设置电话
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        //设置地址
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() +addressBook.getDetail());
        //设置用户名称
        User user = userMapper.select(User.builder().id(BaseContext.getCurrentId()).build());
        orders.setUserName(user.getName());
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //添加订单信息，返回订单id
        orderMapper.insert(orders);
        //根据用户id查询购物车
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getAllCarts(BaseContext.getCurrentId());
        //将购物车集合转换为订单详情集合
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(new Function<ShoppingCart, OrderDetail>() {
            @Override
            public OrderDetail apply(ShoppingCart shoppingCart) {
                OrderDetail orderDetail = new OrderDetail();
                //拷贝属性到订单详情实体
                BeanUtils.copyProperties(shoppingCart, orderDetail);
                //设置id为null
                orderDetail.setId(null);
                //设置订单id
                orderDetail.setOrderId(orders.getId());
                return orderDetail;
            }
        }).collect(Collectors.toList());
        //添加订单详情信息
        orderDetailMapper.insert(orderDetailList);
        //根据用户id删除购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     */
    @Override
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        orderMapper.updatePayMethod(ordersPaymentDTO);
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult historyOrders(int page, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        //设置查询条件
        dto.setStatus(status);
        dto.setUserId(BaseContext.getCurrentId());
        //根据条件查询订单信息
        Page<Orders> pageQuery = orderMapper.findByPageQuery(dto);
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders orders : pageQuery) {
            OrderVO orderVO = new OrderVO();
            //拷贝属性到orderVO
            BeanUtils.copyProperties(orders,orderVO);
            //根据订单id查询订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orders.getId());
            orderVO.setOrderDetailList(orderDetailList);
        }
        return new PageResult(pageQuery.getTotal(),orderVOList);

    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        //根据订单id查询订单信息
        Orders orders = orderMapper.findById(id);
        //根据订单id查询订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(id);
        OrderVO orderVO = new OrderVO();
        //拷贝属性
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //根据订单id查询订单信息
        Orders orders = orderMapper.findById(id);
        //没有此订单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态异常
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //构建更新数据
        Orders order = Orders.builder().id(id).status(Orders.CANCELLED).cancelReason("取消订单").cancelTime(LocalDateTime.now()).build();
        orderMapper.updateCancelOrdersById(order);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(id);
        //将订单详情转换为购物车
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //拷贝属性
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //添加购物车信息
            shoppingCartMapper.addCart(shoppingCart);
        }
    }

}
